<template>
  <div :key="key">
    <div style="margin-top: 36px;"></div>
    <div :id="id" :class="className" :style="{height:(height-40)+'px',width:width}" />
    <div :id="`${id}1`" :style="{height:(height*0.66)+'px',width:width}" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from '../mixins/resize'
import { mapGetters } from 'vuex'
import { findAccountEquity, findInvestManageMaxDown } from '@/api/afterInvest'
import { investGroupNetWorthFit, investGroupNetWorthMaxDown } from '@/api/afterManageCom'
import { findClassifyNetworthByClassifyIdNew, getClassifyMaxDown } from '@/api/groupManage'
import { findCompositionNetworthByCompositionIdNew, getMaxDown, getStrategyAndCompositionByCompositionId } from '@/api/combManage'
import { findIndexByIndexTypeAndIndexTime } from '@/api/policyManage'
import { findIndexMaxDown } from '@/api/policyManage'
import { parseTime, deepClone, downFixed, upFixed, subtract } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: Number,
      default: 200
    },
    id_index: {
      type: Array,
      default: () => {
        return []
      }
    },
    ids: {
      type: String | Number,
      required: true
    },
    contrastOptions_obj: {
      type: Object,
      default: () => {
        return {}
      }
    },
    typePage: {
      type: String,
      default: ''
    },
    userId: {
      type: String | Number,
      default: ''
    },
    name1: {
      type: String,
      default: '拟合'
    },
    name2: {
      type: String,
      default: '风险'
    },
  },
  data() {
    return {
      chart: null,
      chart1: null,
      startTime: '',
      endTime: '',
      xDate: [], // y轴
      fitNetWorth_obj: {}, // 拟合
      netWorth_obj: {}, // 净值
      contrastIndex_obj: {}, // 指数

      // 新增多曲线兼容
      yName_list: [],

      key: 1
    }
  },
  computed: {
    ...mapGetters(['index_dict'])
  },
  watch: {
    typePage() {
      if(this.ids) {
        let PromiseList = []
        this.xDate = []
        this.fitNetWorth_obj = {}
        this.netWorth_obj = {}
        this.yName_list = []
        if(!this.typePage) {
          PromiseList = [this.getFitNetWorthValue(this.ids), this.findInvestManageMaxDown(this.ids)] // 投资管理
        }else if(this.typePage == 'afterManageCom') {
          PromiseList = [this.investGroupNetWorthFit(this.ids), this.investGroupNetWorthMaxDown(this.ids)]
        }else if(this.typePage == 'groupManage') {
          PromiseList = [this.findClassifyNetworthByClassifyId(this.ids), this.getClassifyMaxDown(this.ids)]
        }else if(this.typePage == 'combManage') {
          PromiseList = [this.CombManagefindNetworthById(this.ids), this.CombManagegetMaxDown(this.ids)]
        }else if(this.typePage == 'combManage-strategy') {
          PromiseList = [this.getStrategyAndCompositionByCompositionId(this.ids), this.CombManagegetMaxDown(this.ids)]
        }
        Promise.all(PromiseList).then(res => {
          console.log('数据',res)
          this.fitNetWorth_obj[this.name1] = []
          this.netWorth_obj[this.name2] = []
            
          if(this.typePage == 'groupManage' || this.typePage == 'combManage' || this.typePage == 'combManage-strategy') {
            this.startTime = parseTime(res[0].body[0].date)
            this.endTime = parseTime(res[0].body[res[0].body.length-1].date)
          }else {
            this.startTime = parseTime(res[0].body[0].tradeDate)
            this.endTime = parseTime(res[0].body[res[0].body.length-1].tradeDate)
          }
          this.findIndexByIndexTypeAndIndexTime(this.startTime, this.endTime, this.id_index)
          this.findIndexMaxDown(this.startTime, this.endTime, this.id_index)
           
          const l = deepClone(res[0].body[0].item).length

          res[0].body.forEach(items => {
            if(this.typePage == 'groupManage' || this.typePage == 'combManage' || this.typePage == 'combManage-strategy') {
              this.xDate.push(parseTime(items.date))
              items.item.map((el, i) => {
                if(i==0 && this.id == 'contrastChart1') el.key = '组合'
                if(!(l==2 && el.key == '默认分类')) {
                  if(this.yName_list.indexOf(el.key)==-1) this.yName_list.push(el.key)
                  if(!this.fitNetWorth_obj[el.key]) this.fitNetWorth_obj[el.key] = []
                  this.fitNetWorth_obj[el.key].push(el.netWorth)
                }
              })
            }else {
              this.xDate.push(parseTime(items.tradeDate))
              this.fitNetWorth_obj[this.name1].push(items.investEquity)
            }
          })
          res[1].body.forEach(item => {
            this.netWorth_obj[this.name2].push(item.drawDown)
          })
        })
      }
    },
    ids: {
      handler(id) {
        if(id || id == 0) {
          let PromiseList = []
          this.xDate = []
          if(!this.typePage) {
            PromiseList = [this.getFitNetWorthValue(id), this.findInvestManageMaxDown(id)] // 投资管理
          }else if(this.typePage == 'afterManageCom') {
            PromiseList = [this.investGroupNetWorthFit(id), this.investGroupNetWorthMaxDown(id)]
          }else if(this.typePage == 'groupManage') {
            PromiseList = [this.findClassifyNetworthByClassifyId(id), this.getClassifyMaxDown(id)]
          }else if(this.typePage == 'combManage') {
            PromiseList = [this.CombManagefindNetworthById(id), this.CombManagegetMaxDown(id)]
          }else if(this.typePage == 'combManage-strategy') {
            PromiseList = [this.getStrategyAndCompositionByCompositionId(id), this.CombManagegetMaxDown(id)]
          }
          Promise.all(PromiseList).then(res => {
            console.log('数据',res)
            this.fitNetWorth_obj[this.name1] = []
            this.netWorth_obj[this.name2] = []
            
            if(this.typePage == 'groupManage' || this.typePage == 'combManage' || this.typePage == 'combManage-strategy') {
              this.startTime = parseTime(res[0].body[0].date)
              this.endTime = parseTime(res[0].body[res[0].body.length-1].date)
            }else {
              this.startTime = parseTime(res[0].body[0].tradeDate)
              this.endTime = parseTime(res[0].body[res[0].body.length-1].tradeDate)
            }
            this.findIndexByIndexTypeAndIndexTime(this.startTime, this.endTime, this.id_index)
            this.findIndexMaxDown(this.startTime, this.endTime, this.id_index)
           
            const l = deepClone(res[0].body[0].item).length

            res[0].body.forEach(items => {
              if(this.typePage == 'groupManage' || this.typePage == 'combManage' || this.typePage == 'combManage-strategy') {
                this.xDate.push(parseTime(items.date))
                items.item.map((el, i) => {
                  if(i==0 && this.id == 'contrastChart1') el.key = '组合'
                  if(!(l==2 && el.key == '默认分类')) {
                    if(this.yName_list.indexOf(el.key)==-1) this.yName_list.push(el.key)
                    if(!this.fitNetWorth_obj[el.key]) this.fitNetWorth_obj[el.key] = []
                    this.fitNetWorth_obj[el.key].push(el.netWorth)
                  }
                })
              }else {
                this.xDate.push(parseTime(items.tradeDate))
                this.fitNetWorth_obj[this.name1].push(items.investEquity)
              }
            })
            res[1].body.forEach(item => {
              this.netWorth_obj[this.name2].push(item.drawDown)
            })
          })
        }
      },
      deep: true,
      immediate: true
    },
    id_index: {
      handler(id) {
        if(id.length<6) {
          if(this.startTime&&this.endTime) {
            this.findIndexByIndexTypeAndIndexTime(this.startTime, this.endTime, id)
            this.findIndexMaxDown(this.startTime, this.endTime, id)
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(obj1, obj2) {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart1 = echarts.init(document.getElementById(this.id+'1'))

      const color_list = [
        'rgba(225,103,86,1)', 'rgba(129,183,236,1)', 'rgba(238,203,87,1)', 'rgba(173,224,255,1)', 'rgba(255,155,203,1)',
        '#fff143','#bce672','#f36838','#70f3ff','#d9b611','#96ce54','#ff4777','#44cef6','#eedeb0','#0aa344','#f00056','#4b5cc4','#e29c45',
        '#21a675','#f9906f','#1685a9','#ae7000','#057748','#f05654','#a1afc9','#a78e44','#00e500','#c93756','#065279','#9b4400','#00e09e',
        '#8c4356','#3b2e7e','#7fecad','#f20c00','#426666','#827100','#a4e2c6','#9d2933','#815476','#6e511e','#0eb83a','#b36d61','#edd1d8',
        '#48c0a3','#bf242a','#4c221b','#549688','#60281e','#003371','#789262','#ff7500','#801dae','#758a99','#ffa631','#4c8dae','#50616d','#b0a4e3','#424c50','#cca4e3',
      ]
      const series_obj1 = []
      const series_obj2 = []

      if(Object.keys(obj1).length) {
        Object.keys(obj1).forEach((key, i) => {
          const item = obj1[key]
          series_obj1.push({
            name: key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              color: color_list[i]
            },
            data: item
          })
        })
      }

      if(Object.keys(obj2).length) {
        Object.keys(obj2).forEach((key, i) => {
          let _key = key
          if(i==0 && this.id=="groupManageChart1" && key!=Object.keys(obj1)[0]) _key = Object.keys(obj1)[0] // 解决 分类详情下只有一条策略时，回撤标题为'默认分类'问题
          const item = obj2[key]
          series_obj2.push({
            name: _key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              color: color_list[i]
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: _key=='风险'||_key==this.name2||_key!=key ? 'rgba(225,103,86,0.2)' : 'rgba(0,0,0,0)'
              }, {
                offset: 1,
                color: _key=='风险'||_key==this.name2||_key!=key ? 'rgba(225,103,86,0.2)' : 'rgba(0,0,0,0)'
              }])
            },
            data: item
          })
        })
      }

      this.chart.setOption({
        title: {
          left: 'left',
          text: '收益'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter(params) {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: '15%',
          left: 120,
          right: '20%',
          bottom: '10%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          x: 'left',
          left: '82%',
          top: '10%',
          textStyle: {
            color: '#90979c',
            fontSize: 11,
          }
        },
        calculable: true,
        xAxis: [{
          show: false,
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          splitNumber: 8,
          axisLine: {
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
            interval: 'auto'
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            show: false,
            interval: 'auto',
            // margin: 20,
          },
          data: this.xDate,
        }],
        yAxis: [
          {
            type: 'value',
            min: function(value) {
              const num = value.min - (value.max - value.min)/5
              return downFixed(num, 1)
            },
            max: function(value) {
              const num = value.max + (value.max - value.min)/5
              return upFixed(num, 1)
            },
            splitNumber: 5,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value.toFixed(4)
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [{
          show: false,
          type: 'slider',
          start: 0,
          end: 100,
          realtime: true,
          height: '0%',
          bottom: '18%',
        }, {
          show: false,
          realtime: true, // 实时更新系列的视图
          height: '5%',
          bottom: '5%',
        }],
        series: series_obj1
      })
    
      this.chart1.setOption({
        title: {
          left: 'left',
          text: '回撤'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter(params) {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}%</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: '3%',
          left: 120,
          right: '20%',
          bottom: '38%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          orient: 'vertical',
          x: 'left',
          left: '82%',
          top: '2%',
          textStyle: {
            color: '#90979c',
            fontSize: 11,
          }
        },
        calculable: true,
        xAxis: [{
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          splitNumber: 8,
          axisLine: {
            show: false,
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false,
            alignWithLabel: true,
            interval: 'auto'
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            margin: 20,
            interval: 'auto'
          },
          data: this.xDate,
        }],
        yAxis: [
          {
            type: 'value',
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value+'%'
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [{
          show: false,
          type: 'slider',
          start: 0,
          end: 100,
          realtime: true,
          height: '0%',
          bottom: '18%',
        }, {
          realtime: true, // 实时更新系列的视图
          height: '10%',
          bottom: '5%',
        }],
        series: series_obj2
      })

      this.chart1.on('datazoom', () => {
        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue
        const op = this.chart.getOption()
        const op1 = this.chart1.getOption()
        if(!(this.id == 'contrastChart1' || this.id == 'detailsComn1' || this.id == 'groupManageChart1')) {
          if(this.typePage == 'groupManage' || this.typePage == 'combManage' || this.typePage == 'combManage-strategy') {
            Object.keys(this.fitNetWorth_obj).forEach((key, i) => {
              const list = this.fitNetWorth_obj[key]
              if(list.length-1 >= baseline_i) {
                const baseline_val = this.fitNetWorth_obj[key][baseline_i]
                const data = list.map(item => {
                  if(item != '') {
                    // return (Number(divide(item, baseline_val))+1).toFixed(5)
                    return (Number(subtract(item, baseline_val))+1).toFixed(5)
                  }else if(item == '') {
                    return ''
                  }
                })
                op.series[i].data = data
              }
            })
          }
        }
        op.dataZoom[0].start = op1.dataZoom[0].start
        op.dataZoom[0].end = op1.dataZoom[0].end
        op.dataZoom[1].start = op1.dataZoom[1].start
        op.dataZoom[1].end = op1.dataZoom[1].end
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      })
    },
    getFitNetWorthValue(investId) {
      return new Promise(resolve => {
        findAccountEquity({
          investId
        }).then(res => {
          console.log('拟合净值:', res)
          resolve(res)
        })
      })
    },
    findInvestManageMaxDown(investId) {
      return new Promise(resolve => {
        findInvestManageMaxDown({
          investId
        }).then(res => {
          resolve(res)
        })
      })
    },
    // 指数走势
    findIndexByIndexTypeAndIndexTime(startTime, endTime, indexType) {
      findIndexByIndexTypeAndIndexTime({
        startTime,
        endTime,
        indexType
      }).then(res => {
        this.contrastIndex_obj = {}
        const new_fitNetWorth_obj = {}
        this.yName_list.map(key => {
          new_fitNetWorth_obj[key] = this.fitNetWorth_obj[key]
        })
        this.fitNetWorth_obj = new_fitNetWorth_obj
        Object.keys(res.body).forEach(key => {
          const item = res.body[key]
          const _key = this.contrastOptions_obj[key]
          this.contrastIndex_obj[_key] = item&&Array.isArray(item)&&item.map(item => item.indexValue) || []
        })
        this.fitNetWorth_obj = {
          ...this.fitNetWorth_obj,
          ...this.contrastIndex_obj
        }
        this.chart && this.chart.dispose()
        this.$nextTick(() => {
          this.initChart(this.fitNetWorth_obj, this.netWorth_obj)
        })
      })
    },
    findIndexMaxDown(startTime, endTime, indexType) {
      findIndexMaxDown({
        startTime,
        endTime,
        indexType
      }).then(res => {
        if(res.code == 0) {
          const contrastIndex_obj = {}
          const new_netWorth_obj = {}
          new_netWorth_obj[this.name2] = this.netWorth_obj[this.name2]
          this.netWorth_obj = new_netWorth_obj
          Object.keys(res.body).forEach(key => {
            const item = res.body[key]
            const _key = this.contrastOptions_obj[key]
            contrastIndex_obj[_key] = item&&Array.isArray(item)&&item.map(item => item.drawDown) || []
          })
          this.netWorth_obj = {
            ...this.netWorth_obj,
            ...contrastIndex_obj
          }
          this.chart1 && this.chart1.dispose()
          this.$nextTick(() => {
            this.initChart(this.fitNetWorth_obj, this.netWorth_obj)
          })
        }
      })
    },

    // 投资组合
    investGroupNetWorthFit(groupId) {
      return new Promise(resolve => {
        investGroupNetWorthFit({
          groupId,
          userId: this.userId
        }).then(res => {
          console.log('拟合净值:', res)
          resolve(res)
        })
      })
    },
    investGroupNetWorthMaxDown(groupId) {
      return new Promise(resolve => {
        investGroupNetWorthMaxDown({
          groupId,
          userId: this.userId
        }).then(res => {
          resolve(res)
        })
      })
    },

    // 分类管理
    findClassifyNetworthByClassifyId(classifyId) {
      return new Promise(resolve => {
        findClassifyNetworthByClassifyIdNew({
          classifyId
        }).then(res => {
          console.log('拟合净值:', res)
          resolve(res)
        })
      })
    },
    getClassifyMaxDown(classifyId) {
      return new Promise(resolve => {
        getClassifyMaxDown({
          classifyId
        }).then(res => {
          resolve(res)
        })
      })
    },

    // 组合
    CombManagefindNetworthById(compositionId) {
      return new Promise(resolve => {
        findCompositionNetworthByCompositionIdNew({
          compositionId
        }).then(res => {
          console.log('拟合净值11:', res)
          resolve(res)
        })
      })
    },
    CombManagegetMaxDown(compositionId) {
      return new Promise(resolve => {
        getMaxDown({
          compositionId
        }).then(res => {
          resolve(res)
        })
      })
    },
    getStrategyAndCompositionByCompositionId(compositionId) {
      return new Promise(resolve => {
        getStrategyAndCompositionByCompositionId({
          compositionId
        }).then(res => {
          console.log('拟合净值22:', res)
          resolve(res)
        })
      })
    }
  }
}
</script>
